package cn.itcast.flink.process.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 使用Flink计算引擎实现实时流计算：词频统计WordCount，从TCP Socket消费数据，结果打印控制台
 *
 * @author lilulu
 */
public class StreamProcessStateDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> inputStream = env.socketTextStream("node1", 9999);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<String> wordDataStream = inputStream.flatMap(
                new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String value, Collector<String> collector) throws Exception {
                        String[] words = value.split("\\s+");
                        for (String word : words) {
                            collector.collect(word);
                        }
                    }
                }
        );
        SingleOutputStreamOperator<Tuple2<String, Integer>> tupleDataStream = wordDataStream.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });
//        照单词分组，并且组内求和
        SingleOutputStreamOperator<String> processStream = tupleDataStream.keyBy(tuple -> tuple.f0)
                .process(
//                        分组处理函数，表示对分组流KeyedStream中每组中数据进行处理
                        new KeyedProcessFunction<String, Tuple2<String, Integer>, String>() {
                            private ValueState<Integer> countState = null;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                // 实例状态
                                countState = getRuntimeContext().getState(
                                        new ValueStateDescriptor<Integer>("countState", Integer.class));
                            }

                            @Override
                            public void processElement(Tuple2<String, Integer> value, Context context, Collector<String> collector) throws Exception {
//                                value表示流中每条数据，指的是组内的数据，比如(flink, 1)
                                // a. 获取key以前的词频，从State状态中获取
                                // b. 获取传递进来的值
                                // c. 如果key对数据是第1次出现，以前State中值就是null
                                Integer historyValue = countState.value();
                                Integer currentValue = value.f1;
                                if (historyValue == null) {
                                    countState.update(currentValue);
                                } else {
                                    countState.update(historyValue + currentValue);
                                }

                                String output = context.getCurrentKey() + "->" + countState.value();
                                collector.collect(output);
                            }
                        }
                );
        // 4. 数据终端-sink
        processStream.printToErr();
        // 5. 触发执行-execute
        env.execute("StreamProcessStateDemo");
    }
}